Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:

Could you do this in-place?

Solution:

  1. public class Solution {
  2. public void rotate(int[][] matrix) {
  3. if (matrix == null) {
  4. return;
  5. }
  6. int n = matrix.length;
  7. int layers = n / 2;
  8. for (int k = 0; k < layers; k++) {
  9. for (int i = 0; i < n - 1; i++) {
  10. int tmp = matrix[k][k + i];
  11. // left to top
  12. matrix[k][k + i] = matrix[k + n - 1 - i][k];
  13. // bottom to left
  14. matrix[k + n - 1 - i][k] = matrix[k + n - 1][k + n - 1 - i];
  15. // right to bottom
  16. matrix[k + n - 1][k + n - 1 - i] = matrix[k + i][k + n - 1];
  17. // top to right
  18. matrix[k + i][k + n - 1] = tmp;
  19. }
  20. n -= 2;
  21. }
  22. }
  23. }